package com.baitengsoft.patentapimonitor.api.service.impl;

import com.baitengsoft.patentapimonitor.api.dao.PacApplicantDao;
import com.baitengsoft.patentapimonitor.api.dao.PacIndustryDao;
import com.baitengsoft.patentapimonitor.api.dao.WebApplicantindustryRlatDao;
import com.baitengsoft.patentapimonitor.api.entity.PacIndustryEntity;
import com.baitengsoft.patentapimonitor.api.entity.WebApplicantindustryRlatEntity;
import com.baitengsoft.patentapimonitor.api.model.WebIndustryInfo;
import com.baitengsoft.patentapimonitor.api.service.PacIndustryService;
import com.baitengsoft.patentapimonitor.common.utils.PageResult;
import com.baitengsoft.patentapimonitor.common.utils.Res;
import com.baitengsoft.patentapimonitor.common.utils.SearchParam;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * Created by QEK on 2017/12/19.
 */
@Service
public class PacIndustryServiceImpl extends BaseServiceImpl<PacIndustryEntity> implements PacIndustryService {

    @Autowired
    private PacApplicantDao applicantDao;
    @Autowired
    private PacIndustryDao pacIndustryDao;
    @Autowired
    private WebApplicantindustryRlatDao webApplicantindustryRlatDao;

    /**
     * 分页、条件查询平台的行业
     * @param platformId
     * @param searchParam
     * @return
     */
    public PageResult<PacIndustryEntity> pageSelectPacIndustry(int platformId,SearchParam searchParam) {

        Mapper<PacIndustryEntity> mapper = this.getMapper();
        Example example = new Example(PacIndustryEntity.class);
        //查询当前平台的数据
        example.createCriteria().andEqualTo("platformid",platformId).andEqualTo("status",1);
        //查询条数
        int count = mapper.selectCountByExample(example);
        //排序
        example.orderBy("sort").asc();
        RowBounds rb = new RowBounds(searchParam.getPageNumber(),searchParam.getPageSize());
        List<PacIndustryEntity> list = mapper.selectByExampleAndRowBounds(example,rb);
        return new PageResult<>(list,searchParam.getPageNumber(),searchParam.getPageSize(),count);
    }

    /**
     * 新增行业
     * @param entity
     * @return
     */
    @Override
    public Res addPacIndustry(PacIndustryEntity entity) {
        if (entity.getPlatformid() == null || StringUtils.isBlank(entity.getName()) ){
            return Res.error("参数有误");
        }
        if (entity.getSort() == null || entity.getSort()<1){
            return Res.error("参数有误：序号必须大于0");
        }
        //判断行业名是否存在
        if(IsExist(entity.getName(),entity.getPlatformid())){
            return Res.error("该行业已存在");
        }
        //判断行业排序是否通过
        if (!checkSortIsExitByPlatformId(entity.getPlatformid(), entity.getSort()))
            return Res.error("参数有误：序号已存在");
        PacIndustryEntity pacIndustryDeletedByName = getPacIndustryDeletedByName(entity.getPlatformid(), entity.getName());
        int result;
        if (pacIndustryDeletedByName != null){
            pacIndustryDeletedByName.setSort(entity.getSort());
            pacIndustryDeletedByName.setUpdatedate(new Date());
            pacIndustryDeletedByName.setUpdateoperid(entity.getUpdateoperid());
            pacIndustryDeletedByName.setStatus(1);
            result = pacIndustryDao.updateByPrimaryKey(pacIndustryDeletedByName);
        }else {
            result = saveByNotNull(entity);
        }
        if(result == 1){
            return Res.ok("添加成功！");
        }
        return Res.error("添加失败！");
    }

    /**
     * 根据id查询行业
     * @param id
     * @return
     */
    @Override
    public PacIndustryEntity queryPacIndustryById(Integer id) {
        PacIndustryEntity entity = queryById(id);
        return entity;
    }

    /**
     * 修改行业
     * @param entity
     * @return
     */
    @Override
    public Res updatePacIndustry(PacIndustryEntity entity) {
        if(entity == null ||entity.getName()==null){
            return Res.error("数据有误");
        }
        if (entity.getSort() == null || entity.getSort()<1){
            return Res.error("参数有误：序号必须大于0");
        }
        PacIndustryEntity entity1 = pacIndustryDao.selectByPrimaryKey(entity.getId());
        if(!entity.getName().equals(entity1.getName()) && IsExist(entity.getName(),entity.getPlatformid())){
            return Res.error("该行业已存在");
        }
        if (entity1 == null) return Res.error("参数有误");
        //判断行业排序是否通过
        if (!entity.getSort().equals(entity1.getSort())&&!checkSortIsExitByPlatformId(entity.getPlatformid(), entity.getSort()))
            return Res.error("参数有误：序号已存在");
        entity1.setSort(entity.getSort());
        entity1.setName(entity.getName() == null || entity.getName().isEmpty() ? "" : entity.getName().trim());
        entity1.setUpdatedate(new Date());
        int result = updateByNotNull(entity1);
        if(result == 1){
            return Res.ok("修改成功！");
        }
        return Res.error("修改失败！");
    }

    /**
     * 删除行业
     * @param id
     * @return
     */
    @Override
    public Res deletePacIndustry(Integer id) {
        PacIndustryEntity entity = queryById(id);
        if (entity == null) return Res.error("参数有误，未查询到该行业");
        entity.setStatus(-1);//逻辑删除：1：正常，-1：删除
        int result = updateByNotNull(entity);
        if(result == 1){
            //行业删除之后，原先权利人选择的该行业没了，删除和权力人关联
            Example example = new Example(WebApplicantindustryRlatEntity.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("industryid",id);
            webApplicantindustryRlatDao.deleteByExample(example);
            return Res.ok("删除成功！");
        }
        return Res.error("删除失败！");
    }

    /**
     * 根据平台id获取name和id【下拉框】
     */
    @Override
    public List<WebIndustryInfo> getIndustryInfoByPlatformId(Integer platformId) {
        if (platformId == null) return new ArrayList<>();
        Example example = new Example(PacIndustryEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("platformid",platformId);
        criteria.andEqualTo("status",1);
        example.setOrderByClause("sort asc");
        List<WebIndustryInfo> infos = new ArrayList<>();
        List<PacIndustryEntity> entities = pacIndustryDao.selectByExample(example);
        for (PacIndustryEntity entity :entities){
            WebIndustryInfo info = new WebIndustryInfo();
            info.setIndustryName(entity.getName());
            info.setIndustryId(entity.getId());
            infos.add(info);
        }
        return infos;
    }

    /**
     * 获取本平台下行业Map<id,name>
     */
    @Override
    public Map<Integer, String> getIndustryMapByPlatformId(Integer platformId) {
        List<WebIndustryInfo> infos = getIndustryInfoByPlatformId(platformId);
        Map<Integer, String> map = new LinkedHashMap<>();
        for (WebIndustryInfo info : infos){
            map.put(info.getIndustryId(),info.getIndustryName());
        }
        return map;
    }

    /**
     * 根据权力人Id查询产业ID
     */
    @Override
    public List<Integer> getIndustryIdByApplicentId(Integer applicantId) {
        if (applicantId == null) return new ArrayList<>();
        return pacIndustryDao.getIndustryIdByApplicentId(applicantId);
    }

    /**
     * 据平台Id查询行业Id
     */
    @Override
    public List<Integer> getIndustryIdsByPlatformId(Integer platformid) {
        if (platformid == null) return new ArrayList<>();
        return pacIndustryDao.getIndustryIdsByPlatformId(platformid);
    }

    /**
     * 判断行业排序检查是否通过，true通过，false不通过
     */
    @Override
    public boolean checkSortIsExitByPlatformId(Integer platformid, Integer sort) {
        return !(platformid == null || sort == null) && pacIndustryDao.selectCountByPlatformIdAndSort(platformid, sort) == 0;
    }

    /**
     * 删除数据中是否有该行业
     */
    @Override
    public PacIndustryEntity getPacIndustryDeletedByName(Integer platformid, String name) {
        if (platformid == null || StringUtils.isBlank(name)) return null;
        Example example = new Example(PacIndustryEntity.class);
        example.createCriteria()
                .andEqualTo("platformid",platformid)
                .andEqualTo("name",name)
                .andEqualTo("status",-1);
        List<PacIndustryEntity> list = pacIndustryDao.selectByExample(example);
        if(list.size() > 0){
            return list.get(0);
        }
        return null;
    }

    private void updateApplicantIndustryId(Integer id) {
        applicantDao.updateIndustryToZero(id);
    }


    /**
     * 新增、修改之前判断name是否已经存在
     * @param name
     * @return
     */
    private boolean IsExist(String name,Integer platformId) {
        Mapper<PacIndustryEntity> mapper = this.getMapper();
        Example example = new Example(PacIndustryEntity.class);
        example.createCriteria().andEqualTo("platformid",platformId).andEqualTo("name",name).andEqualTo("status",1);
        List<PacIndustryEntity> list = mapper.selectByExample(example);
        if(list.size() > 0){
            return true;
        }
        return false;
    }

}
